package com.wanli.storemobile.dialog;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Vibrator;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.DialogFragment;

import com.wanli.storemobile.R;
import com.wanli.storemobile.utils.Dp2Px;
import com.wanli.storemobile.utils.GlideUtils;
import com.wanli.storemobile.utils.QRCodeUtil;
import com.wanli.storemobile.utils.ToastUtil;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Author:HWC
 */
public class KdbCodeDialog extends DialogFragment {
    @BindView(R.id.iv_photo)
    ImageView ivPhoto;
    @BindView(R.id.tv_sn_code)
    TextView tvSnCode;
    @BindView(R.id.ll_root)
    LinearLayout llRoot;
    @BindView(R.id.tv_save)
    TextView tvSave;
    private Dialog dialog;
    private Activity mActivity;
    private String payUrl;
    private String code;
    private Bitmap mBitmap;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        initWindow();
        View view = inflater.inflate(R.layout.dialog_kdb_code, null);
        ButterKnife.bind(this, view);
        mActivity = getActivity();
        initView();
        return view;
    }

    public static KdbCodeDialog newInstance(String payUrl, String code) {
        Bundle args = new Bundle();
        KdbCodeDialog fragment = new KdbCodeDialog();
        args.putString("payUrl", payUrl);
        args.putString("code", code);
        fragment.setArguments(args);
        return fragment;
    }

    //    初始化请求
    private void initView() {
        payUrl = getArguments().getString("payUrl");
        code = getArguments().getString("code");
//        mBitmap = QRCodeUtil.createQRCodeBitmap(payUrl, 480, 480);
//        ivPhoto.setImageBitmap(mBitmap);
//        tvSnCode.setText("SN:" + code);

        GlideUtils.loadImage(mActivity, ivPhoto, "https://wnb-dc.oss-cn-qingdao.aliyuncs.com/kdb_qrcode/" + code + ".png");
    }

    //设置window属性
    private void initWindow() {
        //去掉dialog的标题
        dialog = this.getDialog();
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        dialog.setCanceledOnTouchOutside(true);
        dialog.setCancelable(true);
        Window window = dialog.getWindow();
        window.getDecorView().setPadding(0, 0, 0, 0);
        WindowManager.LayoutParams lp = window.getAttributes();
        lp.width = (int) Dp2Px.dp2Px(266);
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
        lp.gravity = Gravity.CENTER;
        window.setAttributes(lp);
        window.setBackgroundDrawable(new ColorDrawable());
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }

    /**
     * view转bitmap
     */
    public Bitmap viewConversionBitmap(View v) {
        int w = v.getWidth();
        int h = v.getHeight();
        Bitmap bmp = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
        Canvas c = new Canvas(bmp);
        c.drawColor(Color.WHITE);
        /** 如果不设置canvas画布为白色，则生成透明 */
        v.layout(0, 0, w, h);
        v.draw(c);
        return bmp;
    }

    /**
     * 屏幕截图保存
     */
    private void saveScreenShot(Bitmap bitmap) {
        String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
        OutputStream outStream = null;
        String filename;//声明文件名
        //以保存时间为文件名
        Date date = new Date(System.currentTimeMillis());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        filename = sdf.format(date);
        File file = new File(extStorageDirectory, filename + ".JPEG");//创建文件，第一个参数为路径，第二个参数为文件名
        try {
            outStream = new FileOutputStream(file);//创建输入流
            bitmap.compress(Bitmap.CompressFormat.JPEG, 90, outStream);
            outStream.close();

            Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
            Uri uri = Uri.fromFile(file);
            intent.setData(uri);
            mActivity.sendBroadcast(intent);
            ToastUtil.showShort("保存相册成功");
            Vibrator vibrator = (Vibrator) mActivity.getSystemService(mActivity.VIBRATOR_SERVICE);
            vibrator.vibrate(200);
        } catch (Exception e) {
            ToastUtil.showShort("保存相册失败，可尝试系统截屏保存");
        }
    }

    @OnClick(R.id.tv_save)
    public void onViewClicked() {
        saveScreenShot(viewConversionBitmap(llRoot));
    }
}
